/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-09 08:40:53
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 16:35:49
 * @FilePath: /operator-manager/src/pages/AccountAccessManage/RoleCreate/index.tsx
 * @Description: 角色管理-角色列表-编辑角色
 */
import { BtnAccessEnum, accessBtnMap } from '@/components/AccessBtn';
import { getRoleDetail, roleUpdate } from '@/services';
import { Access, Link, useAccess, useNavigate, useParams } from '@umijs/max';
import { Button, Result, Space, message } from 'antd';
import { FormInstance } from 'antd/lib';
import { useEffect, useRef, useState } from 'react';
import RoleForm from '../components/RoleForm';
import { roleListPath } from '../constants';
import { RoleTableDataType } from '../type.d';
import styles from './index.less';

const PositionEditPage = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const access = useAccess();
  const [detailInfo, setDetailInfo] = useState<RoleTableDataType>();
  const roleFormRef = useRef<{ roleForm: FormInstance }>();
  const formKey = Date.now();
  const handleToSave = () => {
    if (roleFormRef?.current) {
      const { roleForm } = roleFormRef?.current ?? {};
      roleForm.validateFields().then((values) => {
        console.log('提交给接口的角色数据', values);
        const { menuIdList } = values;
        roleUpdate({
          data: { ...values, id, menuIdList: menuIdList.split(',') },
        }).then((res) => {
          if (res?.success) {
            message.success('保存成功');
            navigate(roleListPath);
          }
        });
      });
    }
  };

  const handleToReturn = () => {
    navigate(roleListPath); //返回角色列表
  };
  useEffect(() => {
    if (id) {
      getRoleDetail({ data: { id } }).then((res) => {
        setDetailInfo(res);
      });
    }
  }, [id]);
  return (
    <Access
      accessible={access.hasBtnPerms(
        accessBtnMap.get(BtnAccessEnum.ROLE_EDIT) as string,
      )}
      fallback={
        <Result
          status="403"
          title="403"
          subTitle="您没有编辑角色的权限"
          extra={
            <Link to={roleListPath}>
              <Button type="primary">返回角色管理</Button>
            </Link>
          }
        />
      }
    >
      <div className={styles.editRolePage}>
        <div className={styles.header}>编辑角色</div>
        <div className={styles.content}>
          <RoleForm
            ref={roleFormRef}
            formKey={formKey}
            initFormValues={detailInfo}
          />
          <Space>
            <Button type="dashed" onClick={handleToReturn}>
              返回
            </Button>
            <Button type="primary" onClick={handleToSave}>
              确定
            </Button>
          </Space>
        </div>
      </div>
    </Access>
  );
};

export default PositionEditPage;
